﻿using Dapr;
using Dapr.Client;
using FrontEnd.Model;
using Microsoft.AspNetCore.Mvc;
using System.Text;

namespace FrontEnd.Controllers;

[Route("api/[controller]")]
[ApiController]
public class DaprPubSubController : ControllerBase
{
    private readonly ILogger<DaprPubSubController> _logger;
    private readonly DaprClient _daprClient;
    public DaprPubSubController(ILogger<DaprPubSubController> logger, DaprClient daprClient)
    {
        _logger = logger;
        _daprClient = daprClient;
    }

    const string PubSubName = "pubsub";
    const string TopicName = "test_topic";

    /// <summary>
    /// 发布（公用）
    /// </summary>
    /// <returns></returns>
    [HttpGet("pub")]
    public async Task<ActionResult> PubAsync()
    {
        _logger.LogInformation("进入 DaprPubSub.PubAsync");
        var data = GetWeatherForecasts();
        await _daprClient.PublishEventAsync(PubSubName, TopicName, data);
        return Ok();
    }

    #region 外部声明式（订阅）
    [HttpPost("sub")]
    public async Task<ActionResult> SubAsync()
    {
        _logger.LogInformation("进入 DaprPubSub.SubAsync");
        Stream stream = Request.Body;
        byte[] buffer = new byte[Request.ContentLength.Value];
        stream.Position = 0L;
        await stream.ReadAsync(buffer, 0, buffer.Length);
        string content = Encoding.UTF8.GetString(buffer);
        _logger.LogInformation($"sub => {content}");
        return Ok(content);
    }
    #endregion

    #region 应用编码式（订阅）
    [Topic(PubSubName, TopicName)]
    [HttpPost("sub_code")]
    public async Task<ActionResult> SubCodeAsync()
    {
        _logger.LogInformation("进入 DaprPubSub.SubCodeAsync");
        Stream stream = Request.Body;
        byte[] buffer = new byte[Request.ContentLength.Value];
        stream.Position = 0L;
        await stream.ReadAsync(buffer, 0, buffer.Length);
        string content = Encoding.UTF8.GetString(buffer);
        _logger.LogInformation($"sub_code => {content}");
        return Ok(content);
    }
    #endregion

    #region 模拟请求数据
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private static WeatherForecast[] GetWeatherForecasts() => Enumerable.Range(1, 3).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    }).ToArray();
    #endregion

}

